//
//  DoImagePickerViewController.m
//  cloudstudy-revive-applestore
//
//  Created by jieer on 2019/1/2.
//  Copyright © 2019年 sdgh. All rights reserved.
//

#import "DoImagePickerViewController.h"
#import "DoImagePickerManager.h"
//#import "DoAssetCollectionViewController.h"
//#import "DoImagePreviewViewController.h"
//#import "DoEditorViewController.h"
#import "UIImage+BoxBlur.h"
#import "AuthorityManager.h"
#import "EDSImageVideoModel.h"

#define MAXNUM 9
#define TAG (indexPath.row)
static NSString* cellId = @"cellId";




@interface DoImagePickerViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
//列表
@property(nonatomic , strong)UICollectionView* collectionView;

@property(nonatomic, strong)NSMutableArray<NSNumber*>* selectBtnList;

//选择图片的list
@property(nonatomic, strong)NSMutableArray<UIImage*>* selectImgList;
//photo对象
@property(nonatomic, strong)Photo *photo;

//@property(nonatomic, strong)DoAssetCollectionViewController* assetVC;

@property(nonatomic, strong)NSMutableDictionary* selectDic;

@property(nonatomic, strong)NSMutableArray* imageList;
@property(nonatomic,strong) UIButton *rightBtn;

@property (nonatomic, strong) NSMutableArray *selImageList;///< 选中图片的编号
@property (nonatomic, strong) NSMutableArray *selVideoList; ///< 选中视频的编号

@end

@implementation DoImagePickerViewController

- (void)dealloc
{
    NSLog(@"%s", __func__);
}

- (instancetype)init {
    if ([super init]) {
        _maxNum = MAXNUM;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 裁剪视频完成后，收到通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cropVideoFinished:) name:kVIDEO_CLIP_FINISHED_NOTI object:nil];
    
    _selImageList = [NSMutableArray new];
    _selVideoList = [NSMutableArray new];
    // Do any additional setup after loading the view from its nib.
    _selectDic = [NSMutableDictionary new];
    _selectBtnList = [NSMutableArray new];
    _selectImgList = [NSMutableArray new];
    //首次进入是全部照片
    self.title = @"所有照片";
    _rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [_rightBtn setTitle:@"下一步" forState:UIControlStateSelected];
     [_rightBtn setTitle:@"取消" forState:UIControlStateNormal];
    [_rightBtn setTintColor:[UIColor whiteColor]];
    _rightBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [_rightBtn setTitleColor:[UIColor colorWithHexString:@"#FF8C05"] forState:UIControlStateSelected];
     [_rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_rightBtn addTarget:self action:@selector(rightBtnPressed)
       forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_rightBtn];
   _rightBtn.selected = NO;
    //通过manager获得所有照片的photo
    self.photo = [[DoImagePickerManager instance] getAllAsset:self.isSelectImage];
    [self loadCollectionView];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
  
}

- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    //引导页
//    [GuideManager showDoImagePickerGuideIfFirstLaunch];
}


-(BOOL)canPop
{
    return YES;
}

#pragma mark - UI

- (void)loadCollectionView
{
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
    //同一行相邻两个cell的最小间距
    layout.minimumInteritemSpacing = 5;
    //最小两行之间的间距
    layout.minimumLineSpacing = 5;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-NAVBAR_HEIGHT_STATUS) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [self.view addSubview:_collectionView];
    
    UINib *cellNib=[UINib nibWithNibName:@"DoImagePickerCollectionViewCell" bundle:nil];
    [_collectionView registerNib:cellNib forCellWithReuseIdentifier:@"DoImagePickerCollectionViewCell"];
    
}



#pragma mark ---- UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.photo.assetList.count+1;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DoImagePickerCollectionViewCell *cell = (DoImagePickerCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"DoImagePickerCollectionViewCell" forIndexPath:indexPath];
    
    if (self.selectPhotoNumType ==SINGLE )
    {
//        if (indexPath.row == 0)
//        {
//            cell.selectBtn.hidden = YES;
//            cell.photoImg.image = [UIImage imageNamed:@"canmera_button"];
//        }
//        else
//        {
            PHAsset* asset = self.photo.assetList[indexPath.row];
            [cell setAsset:asset];
             [cell clear];
            if (indexPath.row == [[_selectBtnList objectAtIndex:0]integerValue])
            {
                cell.selectBtn.hidden = NO;
                cell.selectBtn.selected = YES;
                [cell.selectBtn setImage:[UIImage imageNamed:@"imagepick_select_button"] forState:UIControlStateSelected];
            }
//        }
    }
    else
    {
        PHAsset* asset = [self.photo.assetList objectOrNilAtIndex:indexPath.row];
        if (asset)
        {
            [cell setAsset:asset];
            [cell clear];
            [DoImagePickerManager reloadLabel:_selectBtnList collection:self.collectionView];
        }
    }
    cell.selectBtn.tag = TAG;
    @weakify(self);
    cell.selectBlock = ^(UIButton *btn, int type) {
//        NSLog(@"tangbin");
        @strongify(self);
        [self selectImg:btn type:type];
    };
    return cell;
}

#pragma mark ---- UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return (CGSize){(kScreenWidth-20)/3.f,(kScreenWidth-20)/3.f};
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 5, 5);
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.f;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.f;
}


#pragma mark ---- UICollectionViewDelegate

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


// 选中某item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
 /*
   // __block DoImagePreviewViewController* previewVC= [[DoImagePreviewViewController alloc]init];
//    if (self.selectPhotoNumType==SINGLE )
//    {
//        if (indexPath.row == 0)
//        {
//
//            [AuthorityManager getCameraAuthorityWithAgreeAuthority:^(BOOL isAuthorized) {
//
//                if (isAuthorized)
//                {
//                    UIImagePickerController* imagepicker = [[UIImagePickerController alloc] init];
//                    imagepicker.delegate = self;
//                    imagepicker.sourceType = UIImagePickerControllerSourceTypeCamera;
//                    imagepicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
//                    [self presentViewController:imagepicker animated:YES completion:nil];
//
//                }
//            }];
//        }
//        else
//        {
            PHAsset* asset = self.photo.assetList[indexPath.row];
            __weak __typeof(self)weakSelf = self;

            [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeDefault options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {

                // NSURL * url = [info objectForKey:@"PHImageFileURLKey"];
              //  previewVC.previewImage = result;
               // [weakSelf.navigationController pushViewController:previewVC animated:NO];
            }];

//        }

    }
    else
    {
//        if (indexPath.row == 0)
//        {
//            if (self.selectPhotoNumType == MULTI && _selectBtnList.count == MAXNUM-_photoNum)
//            {
//                [self.view makeToast:[NSString stringWithFormat:@"最多只能选择%ld张图片",MAXNUM-_photoNum]];
//                return;
//            }
//            [AuthorityManager getCameraAuthorityWithAgreeAuthority:^(BOOL isAuthorized) {
//
//                if (isAuthorized)
//                {
//                    for (NSNumber* x in _selectBtnList)
//                    {
//                        NSInteger i = [x integerValue];
//                        PHAsset* asset = self.photo.assetList[i-1];
//
//                        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeDefault options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
//
//                            [_selectImgList addObject:result];
//                        }];
//                    }
//
//                    UIImagePickerController* imagepicker = [[UIImagePickerController alloc] init];
//                    imagepicker.delegate = self;
//                    imagepicker.sourceType = UIImagePickerControllerSourceTypeCamera;
//                    imagepicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
//                    [self presentViewController:imagepicker animated:YES completion:nil];
//
//                }
//            }];
//        }
//        else
//        {
            PHAsset* asset = self.photo.assetList[indexPath.row];

            __weak __typeof(self)weakSelf = self;
            [[PHImageManager defaultManager] requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {

              //  previewVC.previewImage = [UIImage imageWithData:imageData];
               // [weakSelf.navigationController pushViewController:previewVC animated:NO];

            }];


//        }
    }
*/
}

+ (UIImage *)ct_imageFromImage:(UIImage *)image inRect:(CGRect)rect{
    //把像 素rect 转化为 点rect（如无转化则按原图像素取部分图片）
    CGFloat scale = [UIScreen mainScreen].scale;
    CGFloat x= rect.origin.x*scale,y=rect.origin.y*scale,w=rect.size.width*scale,h=rect.size.height*scale;
    CGRect dianRect = CGRectMake(x, y, w, h);
    
    //截取部分图片并生成新图片
    CGImageRef sourceImageRef = [image CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, dianRect);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
    CFRelease(newImageRef);
    return newImage;
}

#pragma mark - 按钮action
////点击选择照片相册
//-(void)selectAssetAblum:(UIButton*)btn
//{
//    if (btn.selected == YES) {
//        btn.selected = NO;
//        [self dismissViewController];
//    }else
//    {
//        btn.selected = YES;
//        _assetVC = [[DoAssetCollectionViewController alloc]init];
//        __weak typeof(self) weakSelf = self;
//        _assetVC.finishSelectAlbum = ^(NSString* title){
//            btn.selected = NO;
//
//            [weakSelf dismissViewController];
//
//            [weakSelf changeAlbum:title];
//        };
//
//
//        [self addChildViewController:_assetVC];
//        _assetVC.view.frame = CGRectMake(0, DEVICE_HEIGHT, DEVICE_WIDTH, 0);
//        [self.view addSubview:_assetVC.view];
//
//        [UIView animateWithDuration:0.5f animations:^{
//            _assetVC.view.frame = CGRectMake(0, -kNavBarHAbove7, DEVICE_WIDTH, DEVICE_HEIGHT+kStatusBarHeight);
//        } completion:nil];
//        //跳转到选择相册，应该把cell复原
//        NSLog(@"_selectBtnList===%@",_selectBtnList);
//        for (UIButton*btn in _selectBtnList) {
//
//            btn.selected = NO;
//            [btn setTitle:@"" forState:UIControlStateNormal];
//        }
//
//        [_selectBtnList removeAllObjects];
//    }
//}

/**
 点击cell上按钮

 @param btn btn description
 @param type 0 图片；1视频；2音频
 */
-(void)selectImg:(UIButton *)btn type:(int)type
{
    NSLog(@"type=%d", type);
    if (type == 0 && self.selVideoList.count > 0)
    {// 选了图片，看看是否有选中的视频，如果有，提示不可以选择
        [SVProgressHUD showInfoWithStatus:@"不支持的文件类型"];
        return;
    }
    else if (type == 1)
    {// 选了视频，看看之前是否有选中的图片，如果有，就实体
        if (self.selImageList.count > 0 || self.photoNum > 0)
        {
            [SVProgressHUD showInfoWithStatus:@"不支持的文件类型"];
            return;
        }
        if (self.selVideoList.count > 0 && btn.selected == NO)
        {
            [SVProgressHUD showInfoWithStatus:@"只能选择一个视频"];
            return;
        }
    }
    
    
    if (btn.selected == NO)
    {// 选中
        if (self.selectPhotoNumType == SINGLE && _selectBtnList.count == 1)
        {
            [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"最多选择%d张图片",1]];
            return;
        }
        else if (self.selectPhotoNumType == MULTI && _selectBtnList.count == self.maxNum-_photoNum)
        {
            [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"最多选择%d张图片",(int)(self.maxNum-_photoNum)]];
            return;
        }
        
        [_selectBtnList addObject:[NSNumber numberWithInteger:btn.tag]];
        if (type == 0)
        {// 图片
            [self.selImageList addObject:@(btn.tag)];
        }
        else if (type == 1)
        {// 视频
            [self.selVideoList addObject:@(btn.tag)];
        }
        if (self.selectPhotoNumType == SINGLE)
        {
            btn.selected = YES;
            [btn setImage:[UIImage imageNamed:@"imagepick_select_button"] forState:UIControlStateSelected];
        }
    }
    else
    {// 不选中
        [_selectBtnList removeObject:[NSNumber numberWithInteger:btn.tag]];
        if (type == 0)
        {// 图片
            [self.selImageList removeObject:@(btn.tag)];
        }
        else if (type == 1)
        {// 视频
            [self.selVideoList removeObject:@(btn.tag)];
        }
        btn.selected = NO;
        [btn setTitle:@"" forState:UIControlStateNormal];
    }
    
    if (self.selectPhotoNumType == MULTI)
    {
        [DoImagePickerManager reloadLabel:_selectBtnList collection:self.collectionView];
    }
    
    //是否显示下一步的按钮
    if (_selectBtnList.count == 0)
        _rightBtn.selected = NO;
    else
        _rightBtn.selected = YES;

}

/**
 裁剪视频完成后，收到通知
 
 @param noti noti description
 */
- (void)cropVideoFinished:(NSNotification *)noti
{
//    NSLog(@"从相册收到通知");
    dispatch_async(dispatch_get_main_queue(), ^{
        EDSImageVideoModel *model = (EDSImageVideoModel *)[noti object];
        NSArray *list = @[model];
        [self dismissViewControllerAnimated:YES completion:^{
            self.selectPhotoBlock(list.mutableCopy, 1);
        }];
    });
}


//点击下一步
-(void)rightBtnPressed
{
    if (_rightBtn.selected )
    {
        NSMutableArray* selectedArr = [NSMutableArray new];
        for (NSNumber* x in _selectBtnList)
        {
            NSInteger i = [x integerValue];
//            NSLog(@"i=%d", i);
            PHAsset* asset = self.photo.assetList[i];
            [selectedArr addObject:asset];
        }
        
        __block NSInteger downloadCount = 0;
        self.imageList = [[NSMutableArray alloc] initWithArray:selectedArr];
        //    [SVProgressHUD showWithStatus:@"正在从iCloud下载图片"];
        for (PHAsset* asset in selectedArr)
        {
            // EDSImageVideoModel
            if (asset.mediaType == PHAssetMediaTypeVideo)
            {// 视频
                [DoImagePickerManager downloadVideoInfoForAssets:asset videoInfo:^(NSURL *videoUrl, float fileSize, double seconds, UIImage *srcImage) {
                    EDSImageVideoModel *model = [EDSImageVideoModel new];
                    model.videoOrAudioUrl = videoUrl;
                    model.fileSize = fileSize;
                    model.seconds = seconds;
                    model.srcImage = srcImage;
                    model.type = 1;
                    
                    // 进入编辑视图控制器
                    UIViewController *videoPreviewVC = [[TYZRouter sharedInstance] getVideoPreviewVC:@{@"videoUrl":model.videoOrAudioUrl, @"isShowCrop":@(YES), @"model":model}];
                    [TYZJumpVCManager pushBaseVC:self pushVC:videoPreviewVC];
                }];
                return;
            }
            
            // 得到的是原图
            [DoImagePickerManager downlodImageForAssets:asset getImage:^(UIImage *image) {
                
                downloadCount++;
                EDSImageVideoModel *model = [EDSImageVideoModel new];
                model.srcImage = image;
                model.type = 0;
                [self.imageList replaceObjectAtIndex:[selectedArr indexOfObject:asset] withObject:model];
                
                //判断是否下载完成
                if (downloadCount == selectedArr.count)
                {
                  //  [SVProgressHUD dismiss];
                    
                    [self dismissViewControllerAnimated:YES completion:^{
                        self.selectPhotoBlock(self.imageList, 0);
                    }];
                }
            }];
            
        }
        return;
    }
    
    [self leftBtnPressed];
    
}

/*
 EDSImageVideoModel *model = selectPhotoList[0];
 // 视频要先进入编辑界面
 UIViewController *videoPreviewVC = [[TYZRouter sharedInstance] getVideoPreviewVC:@{@"videoUrl":model.videoOrAudioUrl, @"isShowCrop":@(NO)}];
 [EDSJumpVCManager pushBaseVC:self pushVC:videoPreviewVC];
 */

//点击返回
-(void)leftBtnPressed
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - 自定义方法
-(void)dismissViewController
{
    [UIView animateWithDuration:1.f animations:^{
      //  _assetVC.view.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 0);
    } completion:^(BOOL finished) {
        
    }];
}


-(void)changeAlbum:(NSString*)title
{
    if ([title isEqualToString:@"所有照片"]) {
        self.photo = [[DoImagePickerManager instance] getAllAsset:self.isSelectImage];
        
        [self.collectionView reloadData];
        
    }else
    {
        self.photo = [[DoImagePickerManager instance] getPhoto:title];
        [self.collectionView reloadData];
    }
}




- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    [_selectImgList addObject:image];
    @weakify(self);
    [picker dismissViewControllerAnimated:YES completion:^{
        @strongify(self);
        [self dismissViewControllerAnimated:NO completion:^{
            self.selectPhotoBlock(self.selectImgList, self.libType);
        }];
        
    }];
}


@end
